/**
 *
 */
package cn.dw.mm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * @author aubrey
 * @date  上午9:10:41
 * 
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {
	/*
	     *采用spring提供的上传文件的方法
	     */
	    @RequestMapping("/upload")
	    @ResponseBody
	    public String  springUpload(HttpServletRequest request) throws IllegalStateException, IOException
	    {
	         //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
	        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
	                request.getSession().getServletContext());
	        //检查form中是否有enctype="multipart/form-data"
	        if(multipartResolver.isMultipart(request))
	        {
	            //将request变成多部分request
	            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
	           //获取multiRequest 中所有的文件名
	            Iterator iter=multiRequest.getFileNames();
	             
	            while(iter.hasNext())
	            {
	                //一次遍历所有文件
	                MultipartFile file=multiRequest.getFile(iter.next().toString());
	                if(file!=null)
	                {
	                    String path="E:/springUpload/"+file.getOriginalFilename();
	                    //上传
	                    file.transferTo(new File(path));
	                }
	                 
	            }
	           
	        }
	        return "success"; 
	    }
	    
	    @RequestMapping("/download")
	    public void download(String fileName,HttpServletRequest req ,HttpServletResponse resp) throws IOException {
	    	File file = new File("E:/springUpload/"+ fileName);
	    	FileInputStream fileIn = new FileInputStream(file);
	    	resp.setContentType("application/x-msdownload;");
	    	resp.setHeader("Content-disposition", "attachment; filename="+file.getName());
	    	resp.setHeader("Content-Length", String.valueOf(file.length()));
	    	OutputStream out= resp.getOutputStream();
	    	int count = 0;
	    	byte[] buf = new byte[1024];
	    	while((count = fileIn.read(buf)) > 0) {
	    		out.write(buf);
	    	}
	    	out.flush();
	    	out.close();
	    }
}

